import Request from './request'
import { reLogged, ajaxError } from '@/components/GlobalModal'
import storage from '@/utils/storageManage'

function errorHandler(errJson) {
  console.log(errJson)
}

const Sapi = new Request({
  baseURL: '/sapi', // baseUrl 方便代理进行拦截
  timeout: 3e4, // 超时
  useGlobalLoding: true, // 是否显示全局Loading
  interceptors: {
    // 实例（单服务器）请求拦截
    requestInterceptor: config => {
      console.log('实例请求拦截成功')
      config.headers = {
        ...config.headers,
        'Authori-zation': `Bearer ${storage.get('token')}`,
      }
      return config
    },
    // 请求拦截失败的处理
    requestCatch: err => {
      console.log('实例请求拦截失败')
      return Promise.reject(err)
    },
    // 实例响应拦截
    responseInterceptor: res => {
      console.log('实例响应拦截成功', res)
      if (res.status === 200) {
        if (res.token) {
          storage.set('token', res.token, res.ex)
        }
        return res
      }
      if (!res.status) {
        ajaxError(['服务异常, 请联系管理员或稍后重试'])
      }
      if (res.status === 410000) {
        reLogged()
      }
      throw res
    },
    // 响应拦截失败的处理
    responseCatch: errJson => {
      console.log(errJson, '实例响应拦截错误')
      // 实例对象自己的错误处理程序
      if (errJson.config.errorBackCaller) {
        return Promise.reject(errJson)
      } else {
        return Promise.reject(errorHandler(errJson))
      }
    },
  },
})

/**
 * 向外暴露的简易方法
 * @param url
 * @param config
 * @returns
 */
export function post(url, data, config = {}) {
  return Sapi.request({ ...config, data, url, method: 'post' })
}
export function put(url, data, config = {}) {
  return Sapi.request({ ...config, data, url, method: 'put' })
}
export function get(url, data, config = {}) {
  return Sapi.request({ ...config, params: data, url, method: 'get' })
}
export function del(url, data, config = {}) {
  return Sapi.request({ ...config, params: data, url, method: 'delete' })
}

export default Sapi
